package com.example.controller;

import com.example.common.RequirePermission;
import com.example.common.Result;
import com.example.service.AdminReportsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 管理员报表控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/admin/reports")
@CrossOrigin
public class AdminReportsController {
    
    @Autowired
    private AdminReportsService adminReportsService;
    
    /**
     * 测试接口
     */
    @GetMapping("/test")
    public Result<String> test() {
        return Result.success("管理员报表API测试成功！包含充值收入统计！当前时间：" + new java.util.Date());
    }
    
    /**
     * 获取管理员报表数据（全平台统计）
     */
    @GetMapping("/data")
    @RequirePermission("admin:reports:view")
    public Result<Map<String, Object>> getAdminReportsData(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(defaultValue = "month") String timeType) {
        try {
            log.info("获取管理员报表数据，参数：startDate={}, endDate={}, timeType={}", startDate, endDate, timeType);
            return adminReportsService.getAdminReportsData(startDate, endDate, timeType);
        } catch (Exception e) {
            log.error("获取管理员报表数据失败", e);
            return Result.error("获取管理员报表数据失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取全平台收入统计（包含成本和利润）
     */
    @GetMapping("/platform-income")
    @RequirePermission("admin:reports:view")
    public Result<Map<String, Object>> getPlatformIncomeStatistics(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        try {
            log.info("获取平台收入统计，参数：startDate={}, endDate={}", startDate, endDate);
            return adminReportsService.getPlatformIncomeStatistics(startDate, endDate);
        } catch (Exception e) {
            log.error("获取平台收入统计失败", e);
            return Result.error("获取平台收入统计失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取全平台收入趋势数据
     */
    @GetMapping("/revenue-trend")
    @RequirePermission("admin:reports:view")
    public Result<Map<String, Object>> getPlatformRevenueTrend(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(defaultValue = "month") String timeType) {
        try {
            log.info("获取平台收入趋势，参数：startDate={}, endDate={}, timeType={}", startDate, endDate, timeType);
            return adminReportsService.getPlatformRevenueTrend(startDate, endDate, timeType);
        } catch (Exception e) {
            log.error("获取平台收入趋势失败", e);
            return Result.error("获取平台收入趋势失败：" + e.getMessage());
        }
    }
    

    
    /**
     * 获取成本分析数据
     */
    @GetMapping("/cost-analysis")
    @RequirePermission("admin:reports:view")
    public Result<Map<String, Object>> getCostAnalysis(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        try {
            log.info("获取成本分析，参数：startDate={}, endDate={}", startDate, endDate);
            return adminReportsService.getCostAnalysis(startDate, endDate);
        } catch (Exception e) {
            log.error("获取成本分析失败", e);
            return Result.error("获取成本分析失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取利润分析数据
     */
    @GetMapping("/profit-analysis")
    @RequirePermission("admin:reports:view")
    public Result<Map<String, Object>> getProfitAnalysis(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        try {
            log.info("获取利润分析，参数：startDate={}, endDate={}", startDate, endDate);
            return adminReportsService.getProfitAnalysis(startDate, endDate);
        } catch (Exception e) {
            log.error("获取利润分析失败", e);
            return Result.error("获取利润分析失败：" + e.getMessage());
        }
    }
    
    /**
     * 测试收入统计数据（用于调试）
     */
    @GetMapping("/test-income")
    public Result<Map<String, Object>> testIncomeData() {
        try {
            log.info("测试收入统计数据");
            return adminReportsService.getPlatformIncomeStatistics(null, null);
        } catch (Exception e) {
            log.error("测试收入统计数据失败", e);
            return Result.error("测试收入统计数据失败：" + e.getMessage());
        }
    }
    
    /**
     * 调试收入统计（无权限检查，用于测试）
     */
    @GetMapping("/debug-income")
    public Result<Map<String, Object>> debugIncomeData() {
        try {
            Map<String, Object> debugData = new HashMap<>();
            
            // 测试今日数据
            BigDecimal todayPackage = adminReportsService.testTodayPackageRevenue();
            BigDecimal todayPurchase = adminReportsService.testTodayPurchaseRevenue();
            BigDecimal todayRecharge = adminReportsService.testTodayRechargeRevenue();
            
            debugData.put("todayPackageRevenue", todayPackage);
            debugData.put("todayPurchaseRevenue", todayPurchase);
            debugData.put("todayRechargeRevenue", todayRecharge);
            debugData.put("todayTotalRevenue", 
                (todayPackage != null ? todayPackage : BigDecimal.ZERO)
                .add(todayPurchase != null ? todayPurchase : BigDecimal.ZERO)
                .add(todayRecharge != null ? todayRecharge : BigDecimal.ZERO));
            
            return Result.success(debugData);
        } catch (Exception e) {
            log.error("调试收入统计失败", e);
            return Result.error("调试收入统计失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取管理员总数据报表
     */
    @GetMapping("/summary")
    @RequirePermission("admin:reports:view")
    public Result<Map<String, Object>> getAdminSummaryReports(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        try {
            log.info("获取管理员总数据报表，参数：startDate={}, endDate={}", startDate, endDate);
            return adminReportsService.getAdminSummaryReports(startDate, endDate);
        } catch (Exception e) {
            log.error("获取管理员总数据报表失败", e);
            return Result.error("获取管理员总数据报表失败：" + e.getMessage());
        }
    }
    
    /**
     * 生成管理员总数据报表（手动触发）
     */
    @PostMapping("/generate")
    @RequirePermission("admin:reports:manage")
    public Result<String> generateAdminReports(@RequestParam(required = false) String reportDate) {
        try {
            log.info("手动生成管理员总数据报表，日期：{}", reportDate);
            return adminReportsService.generateAdminReports(reportDate);
        } catch (Exception e) {
            log.error("生成管理员总数据报表失败", e);
            return Result.error("生成管理员总数据报表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取管理员报表历史数据
     */
    @GetMapping("/history")
    @RequirePermission("admin:reports:view")
    public Result<Map<String, Object>> getAdminReportsHistory(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            log.info("获取管理员报表历史数据，参数：startDate={}, endDate={}, page={}, size={}", 
                    startDate, endDate, page, size);
            return adminReportsService.getAdminReportsHistory(startDate, endDate, page, size);
        } catch (Exception e) {
            log.error("获取管理员报表历史数据失败", e);
            return Result.error("获取管理员报表历史数据失败：" + e.getMessage());
        }
    }
} 